<template>
  <div
    class="content"
    v-loading="listLoading"
    :element-loading-text="listLoadingText"
    element-loading-background="rgba(80, 80, 80, 0.7)"
  >
    <template v-if="boxStatus == 2">
      <TicketAdd
        ref="TicketAdd"
        :ifAddAgain="ifAddAgain"
        @boxStatusChange="boxStatusChange"
        @initSignalPoly="initSignalPoly"
        :userAuthor="userAuthor"
      ></TicketAdd>
    </template>
    <template v-else-if="boxStatus == 3">
      <TicketInfo
        ref="TicketInfo"
        :ticketInfoData="ticketInfoData"
        :userAuthor="userAuthor"
        @boxStatusChange="boxStatusChange"
        @drawSeeAirline="drawSeeAirline"
        @selectAirline="selectAirline"
        @changeAirlineSee="changeAirlineSee"
        @drawPlot="drawPlot"
      ></TicketInfo>
    </template>

    <template v-show="boxStatus == 1">
      <TicketList
        ref="TicketList"
        v-bind="$attrs"
        :boxStatus="boxStatus"
        @boxStatusChange="boxStatusChange"
      ></TicketList>
    </template>
    <MoveBox
      ref="moveBox"
      :box-top="100"
      :box-right="360"
      :box-width="560"
      :box-height="420"
      @closePhoto="closePhoto"
    >
      <!--图片展示-->
      <div class="container">
        <!--图片内容-->
        <ImgBox ref="imgBox" :canvas-width="560" :canvas-height="420" />
        <!--上一页下一页-->
        <div class="leftBtn" @click="previousPhoto">
          <svg-icon icon-class="previous" />
        </div>
        <div class="rightBtn" @click="nextPhoto">
          <svg-icon icon-class="next" />
        </div>
        <!-- 照片信息 -->
        <div class="photoInfo">
          <div>拍摄时间：{{ selectPhoto ? selectPhoto.photo_time : "" }}</div>
          <div>经 度：{{ selectPhoto ? selectPhoto.longitude : "" }}</div>
          <div>拍摄航线：{{ selectPhoto ? selectPhoto.airline_name : "" }}</div>
          <div>纬 度：{{ selectPhoto ? selectPhoto.latitude : "" }}</div>
        </div>
      </div>
    </MoveBox>

    <MoveBox
      ref="panoramaBox"
      :box-top="350"
      :box-right="360"
      :box-width="560"
      :box-height="420"
      @closePhoto="closePanorama"
    >
      <div style="width: 100%; height: 100%">
        <Krpano ref="krpano" :srcId="srcId" :ifTicket="true"></Krpano>
      </div>
    </MoveBox>
  </div>
</template>

<script>
import TicketList from "./view5Comps/ticketList.vue";
import TicketAdd from "./view5Comps/ticketAdd.vue";
import TicketInfo from "./view5Comps/ticketInfo.vue";

import { getPhotoShadow, getSignalPolygon } from "@/api/kanban";
import { taskPrdResult, nestRemoved } from "@/api/view5";

import MoveBox from "@/views/components/boxComps/moveBox.vue";
import ImgBox from "@/views/components/boxComps/imgBox.vue";

import Krpano from "@/views/components/PanoramaComps/krpano.vue";

window.airlineMapLayer = null; // 查询航线图层
window.airlinePlotLayer = null; // 查询地块图层

var layerPolygon; // 图片范围图层
var pointArr = []; // 照片点集合

var flyPoint = []; // 飞点
var layerPolygon = null; //图片投影

var triDMark; // 三维图层
var towDMap; // 二维图层

var lineColor = ["#f0f", "#0f0", "#00f"];
export default {
  name: "v5",
  props: {
    // dateValue: {
    //   type: Array,
    //   default: () => [],
    // },
    ticketLineStatus: {
      default() {
        return false;
      },
    },
  },
  watch: {},
  components: {
    TicketList,
    TicketAdd,
    TicketInfo,
    MoveBox,
    ImgBox,
    Krpano,
  },
  data() {
    return {
      boxStatus: 1, // 1-列表 2-新增 3-详情
      ticketInfoData: {}, // 选中任务
      ifAddAgain: false, // 是否再次提交

      userAuthor: null,
      ticketLoading: false, // 指点任务加载
      workSmallWindowShow: true, // 小窗口
      photoHandler: null, // 图片点击事件
      photoList: [], // 图片列表

      selectPhoto: null, // 选中的图片
      photoIndex: "", // 选中图片的序号
      photoFirst: false, // 第一次点击图片

      panoramaUrl: null, // 全景链接
      srcId: "",

      nestList: [], // 机巢列表
      nestSearch: null, // 航线出发的机巢

      textareaPlaceholder: "请输入内容", // 提示字

      clickTimes: 0,

      listLoading: false,
      listLoadingText: "",
      lineNameLength: "",

      ifLine: true, // 是否有航线
      ifPhoto: true, // 是否有图片
      ifNest: true, // 是否找到机场
    };
  },
  created() {
    this.userAuthor = this.$store.getters.userAuth;
  },
  mounted() {
    const that = this;
    // 创建新建图层
    that.initData();
    that.initBus();
  },
  methods: {
    initData() {
      this.$emit("ticketLineStatusChange", false);
      // ? 获取VueX里面信息
      this.nestList = this.$store.getters.nestList;

      airlineMapLayer = CesiumUtil.CreateLayer("airlineMapLayer");
      airlinePlotLayer = CesiumUtil.CreateLayer("airlinePlotLayer");
    },
    initBus() {
      // 显示指点飞行按钮
      this.$bus.emit("bottomButtonState", 1);
    },
    // ? 文本框获取焦点
    textareaFocus() {
      this.textareaPlaceholder = "";
    },
    // ? 文本框失去焦点
    textareaBlur() {
      this.textareaPlaceholder = "请输入内容";
    },

    // 任务页面类型变更
    boxStatusChange(type) {
      this.boxStatus = type;

      // 初始化图层
      // 图片弹框
      this.$refs.moveBox.toggleShow(false);
      this.removePhotoHandler();
      airlineMapLayer && airlineMapLayer.entities.removeAll();
      airlinePlotLayer && airlinePlotLayer.entities.removeAll();
      // 全景弹框
      this.$refs.panoramaBox.toggleShow(false);
      // 三维图层
      triDMark && viewer.scene.primitives.remove(triDMark);
      // 二维图层
      towDMap && CesiumUtil.RemoveMyMap(towDMap);

      SignalLayer && SignalLayer.entities.removeAll();
      switch (type) {
        case 1:
          // 列表
          this.$parent.$parent.ticketLineStatus = false;
          this.$bus.emit("toggleNestLayer", true);
          break;
        case 2:
          // 新增
          this.$parent.$parent.ticketLineStatus = true;
          this.$bus.emit("toggleNestLayer", false);
          // 信号覆盖图层
          this.initSignalPoly(120);
          break;
        case 3:
          break;
        default:
          break;
      }
    },

    // 信号覆盖图层
    async initSignalPoly(height) {
      let removedNestRes = await nestRemoved({
        dept_id: this.$store.getters.deptId,
      });

      let removedNestList = [];
      if (removedNestRes.error_code == 0) {
        removedNestList = removedNestRes.data || [];
      }

      SignalLayer && SignalLayer.entities.removeAll();
      getSignalPolygon({
        dept_id: this.$store.getters.deptId,
        real_height: height,
      }).then((res) => {
        var polyjson = res["data"];
        polyjson.features = polyjson.features.filter((item) => {
          let nestCode = item.properties.name;
          let findCode = removedNestList.find((code) => {
            return code == nestCode;
          });
          if (!findCode) {
            return item;
          }
        });

        CesiumUtil.LoadGeoJsonPolygon(polyjson, SignalLayer, {
          color: "rgba(44, 232, 110, 0.2)",
          polyline: true,
        });
      });
    },
    //  查看航线
    drawSeeAirline(data) {
      let that = this;

      // 初始化

      // 图片弹框
      that.$refs.moveBox.toggleShow(false);
      that.photoList = [];

      that.removePhotoHandler();
      that.initPhotoMapHandler();
      that.photoFirst = false;
      // 清空图层
      airlineMapLayer && airlineMapLayer.entities.removeAll();

      this.openTask(data);
      // ? 找机巢
      this.nestSearch = this.$store.getters.nestList.find((e) => {
        if (e.nest_code === this.ticketInfoData.nest_code) {
          return e;
        }
      });
      if (!this.nestSearch) {
        this.$message.warning("未找到机场");
      }
      data.flight_records.forEach((item, index) => {
        this.drawAirline(item, index);
        if (item.photos) {
          item.photos.map((photo, photoIndex) => {
            photo.photo_id = item.flight_record_code + "--photo--" + photoIndex;
            photo.flight_record_code = item.flight_record_code;
            photo.airline_name = item.airline_name;
            that.photoList.push(photo);
          });
        }
      });
      this.drawAirlinePhoto();
      setTimeout(() => {
        viewer.flyTo(airlineMapLayer);
      }, 1000);
    },
    // 地块
    // 绘制查看地块
    drawPlot() {
      // airlinePlotLayer && airlinePlotLayer.entities.removeAll();

      let plot = this.ticketInfoData.plot;
      if (!plot.plot_data) {
        this.$message.warning("无地块信息");
        return;
      }
      let list2D = plot.plot_data.coordinates;
      let p3 = [];

      if (plot.plot_shape == 1) {
        p3 = list2D;
      } else if (plot.plot_shape == 3) {
        list2D[0].forEach((item) => {
          p3.push(item[0], item[1], item[2] || 100);
        });
      } else {
        list2D.forEach((item) => {
          p3.push(item[0], item[1], item[2] || 100);
        });
      }
      let list3D = Cesium.Cartesian3.fromDegreesArrayHeights(p3);

      switch (plot.plot_shape) {
        case 1:
          let ellipseOption = {
            name: "查看点地块",
            type: "查看点地块",
            radius: plot.radius,
            color: "#00ffff",
          };
          CesiumUtil.drawEllipse(list3D[0], airlinePlotLayer, ellipseOption);
          let ellipseLineOption = {
            name: "点地块线",
            type: "点地块线",
          };
          CesiumUtil.drawPolyline(list3D, airlinePlotLayer, ellipseLineOption);
          break;
        case 2:
          let lineOption = {
            name: "查看线地块",
            type: "查看线地块",
          };
          CesiumUtil.drawPolyline(list3D, airlinePlotLayer, lineOption);

          list2D.forEach((point, index) => {
            if (index === list2D.length - 1) {
              return;
            } else {
              CesiumUtil.drawLineBuffer(
                [point, list2D[index + 1]],
                plot.width,
                airlinePlotLayer
              );
            }
          });
          break;
        case 3:
          let polygonOption = {
            name: "查看面地块",
            type: "查看面地块",
            color: "#0000FF",
          };
          CesiumUtil.drawPolygon(list3D, airlinePlotLayer, polygonOption);

          let polygonLineOption = {
            name: "面地块线",
            type: "面地块线",
          };
          CesiumUtil.drawPolyline(list3D, airlinePlotLayer, polygonLineOption);
        default:
          break;
      }
      viewer.flyTo(airlinePlotLayer);
    },

    // 绘制查看航线
    drawAirline(data, index) {
      // ? 航线
      let linePoint = data.airline;
      let nest = this.nestSearch;

      if (linePoint.length > 0) {
        if (nest) {
          let startDashLineObj = {
            type: "line",
            id: data.flight_record_code + "--" + index + "开始",
            name: data.flight_record_code,
            isheight: true,
            color: "#fff",
            positions: [
              nest.position.longitude,
              nest.position.latitude,
              nest.position.altitude,
              nest.position.longitude,
              nest.position.latitude,
              linePoint[0][2] + nest.position.altitude,
              linePoint[0][0],
              linePoint[0][1],
              linePoint[0][2] + nest.position.altitude,
            ],
          };
          CesiumUtil.AddDashLine(startDashLineObj, airlineMapLayer);
          let endDashLineObj = {
            type: "line",
            id: data.flight_record_code + "--" + index + "结束",
            name: data.flight_record_code,
            isheight: true,
            color: "#eee",
            positions: [
              linePoint[linePoint.length - 1][0],
              linePoint[linePoint.length - 1][1],
              linePoint[linePoint.length - 1][2] + nest.position.altitude,
              nest.position.longitude,
              nest.position.latitude,
              linePoint[0][2] + nest.position.altitude,
              nest.position.longitude,
              nest.position.latitude,
              nest.position.altitude,
            ],
          };
          CesiumUtil.AddDashLine(endDashLineObj, airlineMapLayer);
        }
        let airLine = [];
        linePoint.forEach((e) => {
          airLine.push(
            e[0],
            e[1],
            e[2] + (nest ? nest.position.altitude : 100)
          );
        });
        var airLineLayer = {
          id: data.flight_record_code + "--" + index,
          name: data.flight_record_code,
          type: "airline",
          positions: airLine,
          color: "#1cc1ff",
          isheight: true,
        };
        CesiumUtil.AddLine(airLineLayer, airlineMapLayer);
      } else {
        that.$message.info("无航线数据");
      }
    },
    // 绘制航线的图片
    drawAirlinePhoto() {
      let that = this;
      this.photoList.forEach((item, index) => {
        let pointPosition = Cesium.Cartesian3.fromDegrees(
          item.longitude,
          item.latitude,
          item?.altitude || that.nestSearch.position.altitude
        );
        const pointOption = {
          id: item.photo_id,
          name: item.flight_record_code,
          type: "point",
          color: "rgba(255, 255, 255, 0.9)",
          colorAlpha: 0.9,
          size: 10,
        };

        let pointLayer = CesiumUtil.drawPoint(
          pointPosition,
          airlineMapLayer,
          pointOption
        );
        pointArr.push(pointLayer);
      });
      that.photoIndex = 0;
    },
    // 打开成果
    async openTask(data) {
      let that = this;
      // 全景弹框
      that.$refs.panoramaBox.toggleShow(false);
      // 三维图层
      triDMark && viewer.scene.primitives.remove(triDMark);
      // 二维图层
      towDMap && CesiumUtil.RemoveMyMap(towDMap);

      // 获取成果
      let taskRes = await taskPrdResult({
        aim: this.ticketInfoData.aim,
        task_id: data.task_id,
      });
      console.log("taskRes", taskRes);
      let taskData = null;
      if (taskRes.error_code == 0) {
        taskData = taskRes.data;
      }
      if (!taskData.url) {
        return;
      }
      if (this.ticketInfoData.aim == 1 || this.ticketInfoData.aim == 3) {
        // "拍照";
        // "全覆盖";
        this.openPhoto();
      } else if (this.ticketInfoData.aim == 4 && taskData) {
        // "全景";
        this.srcId = "";
        this.$refs.panoramaBox.toggleShow(true);
        let Kid = taskData.url.split("?scene_id=")[1];
        this.$nextTick(() => {
          this.srcId = Kid;
        });
        // this.panoramaUrl = taskData.url;
      } else if (this.ticketInfoData.aim == 5 && taskData) {
        // "正射";
        if (towDMap) {
          CesiumUtil.RemoveMyMap(towDMap);
        }
        if (taskData.url) {
          CesiumUtil.AddMyMap(taskData.url).then((res) => {
            towDMap = res;
          });
        }
      } else if (this.ticketInfoData.aim == 6 && taskData) {
        // "三维";
        if (triDMark) {
          viewer.scene.primitives.remove(triDMark);
        }
        triDMark = new Cesium.Cesium3DTileset({
          url: taskData.url,
        });
        viewer.scene.primitives.add(triDMark);
        triDMark.readyPromise.then(function (argument) {
          viewer.scene.globe.depthTestAgainstTerrain = false;
        });
      }
    },

    selectAirline(code) {
      airlineMapLayer.entities.values.map((item) => {
        if (item.type == "airline") {
          if (item.id.split("--")[0] == code) {
            item.polyline.material = Cesium.Color.fromCssColorString("#00f");
            viewer.flyTo(item);
          } else {
            item.polyline.material = Cesium.Color.fromCssColorString("#1cc1ff");
          }
        }
      });
    },
    // 显示隐藏航线
    changeAirlineSee(code, flag) {
      airlineMapLayer.entities.values.map((item) => {
        if (item.name == code) {
          item.show = flag;
        }
      });
    },
    // ! 删除 航线图层
    destroyQueryLineLayer() {
      if (airlineMapLayer) {
        airlineMapLayer.entities.removeAll();
        airlineMapLayer = null;
      }
      if (airlinePlotLayer) {
        airlinePlotLayer.entities.removeAll();
        airlinePlotLayer = null;
      }
    },
    // 图片控制
    // * 注册图片点 点击事件
    initPhotoMapHandler() {
      const that = this;
      that.photoHandler = new Cesium.ScreenSpaceEventHandler(
        viewer.scene.canvas
      );
      that.photoHandler.setInputAction(function (e) {
        that.photoMapClick(e);
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },
    // * 图片点 点击事件
    photoMapClick(val) {
      const that = this;
      const obj = CesiumUtil.LeftClick(val);
      if (obj.pick && obj.pick.id) {
        // 查找对应图片
        that.photoList.forEach((item, index) => {
          if (item.photo_id === obj.pick.id.id) {
            that.photoIndex = index;
            that.openPhoto();
          }
        });
      }
    },
    // * 注销图片点 点击事件
    removePhotoHandler() {
      if (this.photoHandler) {
        this.photoHandler.removeInputAction(
          Cesium.ScreenSpaceEventType.LEFT_CLICK
        );
      }
    },
    // * 打开图片弹框
    openPhoto() {
      this.selectPhoto = this.photoList[this.photoIndex];
      let findLine = this.$refs.TicketInfo.findLine(
        this.selectPhoto.flight_record_code
      );
      if (!findLine) {
        this.closePhoto();
        this.$refs.moveBox.toggleShow(false);
        return;
      }

      this.$refs.moveBox.toggleShow(true);
      setTimeout(() => {
        this.$refs.imgBox.SetImage(this.selectPhoto.photo_file_url);
      }, 0);
      getPhotoShadow({ photo_id: this.selectPhoto.photo_info_code }).then(
        ({ data }) => {
          // 清空投影
          layerPolygon && airlineMapLayer.entities.remove(layerPolygon);

          if (!data) {
            return;
          }
          let photoPolygon = [];
          if (data.location.type === "Polygon") {
            // 图片投影点位
            data.location.coordinates[0].forEach((e) => {
              photoPolygon.push(e[0], e[1]);
            });
            // 图片投影图层
            let photoLayer = {
              type: "photo_view",
              positions: photoPolygon,
              clamp: true,
              color: "rgba(255,255,2,0.5)",
            };
            layerPolygon = CesiumUtil.AddPolygon(photoLayer, airlineMapLayer);
          }
        }
      );

      let findPhoto = null;
      pointArr.forEach((e) => {
        if (e.id === this.selectPhoto.photo_id) {
          findPhoto = e;
          e._point._color._value = new Cesium.Color(1, 0, 0, 1);
        } else {
          e._point._color._value = new Cesium.Color(1, 1, 1, 1);
        }
      });
      if (!this.photoFirst) {
        viewer.flyTo(findPhoto);
        this.photoFirst = true;
      }
    },
    // * 关闭图片弹框
    closePhoto() {
      // 清空投影
      if (layerPolygon) {
        airlineMapLayer.entities.remove(layerPolygon);
      }
    },
    // 上一张
    previousPhoto() {
      if (this.photoIndex > 0) {
        this.photoIndex--;
      } else if (this.photoList.length > 0) {
        this.photoIndex = this.photoList.length - 1;
      }
      this.openPhoto();
    },
    // 下一张
    nextPhoto() {
      if (this.photoIndex < this.photoList.length - 1) {
        this.photoIndex++;
      } else {
        this.photoIndex = 0;
      }
      this.openPhoto();
    },

    // 全景
    // * 关闭全景弹框
    closePanorama() {
      this.panoramaUrl = null;
    },
  },
  computed: {},

  beforeDestroy() {
    this.destroyQueryLineLayer(); // 删除查看图层
    this.removePhotoHandler(); // 删除图片事件

    this.$emit("ticketLineStatusChange", false);

    // 关闭定时器
    clearInterval(this.workTime);
    this.workTime = null;
  },
};
</script>

<style lang="scss" scoped>
$color1: #18abf3;
$color2: rgba(44, 232, 110, 0.5);
.content {
  padding: 10px;
  color: white;
  text-align: center;
  height: 100%;

  .container {
    position: relative;

    .leftBtn {
      cursor: pointer;
      position: absolute;
      left: 0;
      top: 180px;
      background-color: rgba(200, 200, 200, 0.6);
      border-radius: 4px;

      .svg-icon {
        width: 30px;
        height: 60px;
      }
    }

    .rightBtn {
      cursor: pointer;
      position: absolute;
      right: 0;
      top: 180px;
      background-color: rgba(200, 200, 200, 0.6);
      border-radius: 4px;

      .svg-icon {
        width: 30px;
        height: 60px;
      }
    }

    .photoInfo {
      position: absolute;
      width: 100%;
      bottom: 0;
      left: 0;
      color: white;
      display: grid;
      grid-template-rows: 1fr auto;
      grid-template-columns: 1fr auto;
      font-size: 12px;
      padding: 10px;
      grid-row-gap: 5px;

      div {
        text-align: start;
      }
    }
  }
}

.full-mask {
  position: fixed;
  z-index: 20020;
  background-color: rgba(0, 0, 0, 0);
  margin: 0;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  -webkit-transition: opacity 0.3s;
  transition: opacity 0.3s;
  box-sizing: inherit;
}
</style>
